package ks.client.controllers;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import ks.client.gamefactory.GameWindow;
import ks.common.games.Solitaire;
import ks.framework.common.Message;
import ks.framework.interfaces.IProcessMessage;
import ks.launcher.Main;

/**
 * PLEASE NOTE. This code is provided as is but is not really the
 * proper way this is supposed to work.
 * <p>
 * You'll need to better integrate this logic into your own GUIs.
 * 
 * @author George Heineman
 *
 */
public class StartGameController implements IProcessMessage {
	/** Used to extract information from started message. */
	public static final String variationAttribute = "variation";
	
	/** Used to extract information from started message. */
	public static final String seedAttribute = "seed";

	/** Game actually started. */
	GameWindow gw;
	
	@Override
	public boolean process(Message m) {
		try {
			// started messages...
			Node started = m.contents();
			
			// Find out its attributes.
			NamedNodeMap nnp = started.getAttributes();
			
			Node variation = nnp.getNamedItem(variationAttribute);
			Node seed = nnp.getNamedItem(seedAttribute);
		
			String varType = variation.getNodeValue();
			String seedVal = seed.getNodeValue();
			int seedInt = Integer.valueOf(seedVal);
			Class<?> c = Class.forName(varType);
			Solitaire sol = (Solitaire) c.newInstance();
		
			// do it!
			gw = Main.generateWindow(sol, seedInt);
			gw.setVisible(true);
			return true;
		} catch (ClassNotFoundException cnfe) {
			return false;
		} catch (InstantiationException e) {
			return false;
		} catch (IllegalAccessException e) {
			return false;
		}
	}

	/** Mostly for debugging... */
	public GameWindow getGameWindow () { 
		return gw;
	}
	
}
